<template>
  <div class='container'>
    <el-card class="box-card">
      <!-- 头部菜单 -->
      <div class="menu">
        <!-- 学科搜索 -->
        <el-form ref="form" :model="form" label-width="80px" :inline="true">
          <el-form-item label="学科名称" prop="subjectName">
            <el-input v-model.trim="form.subjectName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetFields">清除</el-button>
            <el-button :loading="isLoading" type="primary" @click="hSearchName">搜索</el-button>
          </el-form-item>
        </el-form>
        <!-- 新增学科 -->
        <el-button
        class="addsub"
        icon="el-icon-edit"
        type="success"
        @click="dialogFormVisibleAdd = true">新增学科</el-button>
      </div>
      <!-- 数据提示 -->
      <el-alert
        :title="'数据共有' + total_count + '条'"
        type="info"
        show-icon
        :closable="false">
      </el-alert>
      <!-- 表格主体 -->
      <el-table
        v-loading="isLoading"
        class="subtable"
        :data="tableData"
        style="width: 100%"
        fit>
        <el-table-column
          prop="id"
          label="序号"
          type="index"
          :index="(requestParams.pagesize * (requestParams.page-1) + 1)">
        </el-table-column>
        <el-table-column
          prop="subjectName"
          label="学科名称">
        </el-table-column>
        <el-table-column
          prop="username"
          label="创建者">
        </el-table-column>
         <el-table-column
          prop="addDate"
          label="创建日期">
            <template slot-scope="scope">
              {{ scope.row.addDate | fDateFormatter }}
            </template>
        </el-table-column>
         <el-table-column
          prop="isFrontDisplay"
          label="前台是否显示">
           <template slot-scope="scope">
             <span v-if="scope.row.isFrontDisplay">{{"是"}}</span>
             <span v-else>{{"否"}}</span>
           </template>
        </el-table-column>
         <el-table-column
          prop="twoLevelDirectory"
          label="二级目录">
        </el-table-column>
         <el-table-column
          prop="tags"
          label="标签">
        </el-table-column>
         <el-table-column
          prop="totals"
          label="题目数量">
        </el-table-column>
         <el-table-column
          label="操作"
          width="240">
          <template slot-scope="scope">
            <!-- 跳转链接 -->
            <el-button type="text" @click="hJump(scope.row,'directorys')">学科分类</el-button>
            <el-button type="text" @click="hJump(scope.row,'tags')">学科标签</el-button>
            <el-button type="text" @click="modSubject(scope.row.id)">修改</el-button>
            <el-button type="text" @click="delSubject(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部分页 -->
      <el-pagination
        :disabled="isLoading"
        class="subpage"
        background
        @size-change="hSizeChange"
        @current-change="hPageChange"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="10"
        layout="prev, pager, next, sizes, jumper"
        :total="total_count">
      </el-pagination>
    </el-card>
    <!-- 新增弹出框 -->
    <el-dialog title="新增学科" :visible.sync="dialogFormVisibleAdd" width="20%">
      <el-form ref="addform" :rules="rules" :model="addform" label-width="80px">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input placeholder="请输入学科名称" v-model="addform.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            style="display: inline"
            v-model="addform.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="addSubject">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改弹出框 -->
    <el-dialog title="修改学科" :visible.sync="dialogFormVisibleMod" width="20%">
      <el-form ref="modform" :rules="modRules" :model="modform" label-width="80px">
        <el-form-item label="学科名称" prop="subjectName">
             <el-input v-model="modform.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            style="display: inline"
            v-model="modform.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibleMod = false">取 消</el-button>
          <el-button type="primary" @click="updateSubject">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 引入各项Ajax方法
import { list, add, detail, update, remove } from '@/api/hmmm/subjects.js'
export default {
  data () {
    return {
      // -- 渲染页面的请求参数 --
      requestParams: '',
      // -- 搜索框 --
      form: {
        subjectName: ''
      },
      // -- 表格数据 --
      tableData: [],
      // 数据总数
      total_count: 0,
      // -- 分页 --
      // 当前页
      page: 1,
      // 总页数
      pages: '',
      // 每页显示条数
      pagesize: 10,
      // 弹出框 - 新增
      dialogFormVisibleAdd: false,
      // 弹出框 - 修改
      dialogFormVisibleMod: false,
      // -- 表单验证 --
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ],
        isFrontDisplay: [
          { required: true }
        ]
      },
      modRules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      },
      // -- 增加学科 --
      addform: {
        subjectName: '',
        // 默认显示
        isFrontDisplay: true
      },
      // -- 修改 & 删除 共用的id --
      id: '',
      // 修改学科
      modform: {
        subjectName: '',
        isFrontDisplay: true
      },
      // 渲染页面、查询、分页的loading效果
      isLoading: false
    }
  },
  // -- 日期格式化 --
  filters: {
    fDateFormatter (p) {
      // 补零函数
      function fAddZero (params) {
        return params < 10 ? '0' + params : params
      }
      const date = new Date(p)
      const y = date.getFullYear()
      const m = fAddZero(date.getMonth() + 1)
      const r = fAddZero(date.getDate())
      const h = fAddZero(date.getHours())
      const i = fAddZero(date.getMinutes())
      const s = fAddZero(date.getSeconds())
      return y + '-' + m + '-' + r + ' ' + h + ':' + i + ':' + s
    }
  },
  created () {
    // 打开页面，获取请求参数，渲染页面
    this.requestParams = {
      page: 1,
      pagesize: 10,
      subjectName: null
    }
    this.getSubjects()
  },
  methods: {
    // -- 获取学科列表 --
    async getSubjects () {
      this.isLoading = true
      try {
        const res = await list(this.requestParams)
        // console.log(res)
        this.isLoading = false
        console.log(res.data.items)
        this.tableData = res.data.items
        this.total_count = res.data.counts
      } catch (err) {
        this.isLoading = false
        console.log(err)
      }
    },
    // -- 实现分页和按页筛选 --
    hSizeChange (pagesize) {
      // console.log(pagesize)
      this.requestParams.pagesize = pagesize
      this.getSubjects()
    },
    hPageChange (page) {
      // console.log(page)
      this.requestParams.page = page
      this.getSubjects()
    },
    // 路由跳转 - encodeURIComponent转译
    hJump (item, name) {
      this.$router.push('/subjects/' + name + '?id=' + item.id + '&name=' + encodeURIComponent(item.subjectName))
    },
    // hDirectorys (item) {
    //   this.$router.push('/subjects/directorys?id=' + item.id + '&name=' + item.subjectName)
    // },
    // hTags (item) {
    //   this.$router.push('/subjects/tags?id=' + item.id + '&name=' + item.subjectName)
    // },
    // -- 搜索学科 --
    // 清除数据
    resetFields () {
      this.$refs.form.resetFields()
      this.getSubjects()
    },
    hSearchName () {
      this.requestParams.page = 1
      this.requestParams.subjectName = this.form.subjectName
      this.getSubjects()
    },
    // -- 新增学科 --
    addSubject () {
      this.isFrontDisplay = this.isFrontDisplay ? 1 : 0
      this.$refs.addform.validate(async (valid) => {
        if (valid) {
          try {
            const res = await add(this.addform)
            console.log(res)
            this.$message.success('新增学科成功')
            this.getSubjects()
            // 清空表单信息
            this.$refs.addform.resetFields()
            this.dialogFormVisibleAdd = false
          } catch (err) {
            console.log(err)
            this.$message.error('新增学科失败')
            this.dialogFormVisibleAdd = false
          }
        }
      })
    },
    // -- 修改学科 --
    // 数据回填
    async modSubject (id) {
      this.dialogFormVisibleMod = true
      this.id = id
      try {
        const res = await detail({ id })
        console.log('当前行数据', res)
        this.modform.subjectName = res.data.subjectName
        if (res.data.isFrontDisplay) {
          this.modform.isFrontDisplay = true
        } else {
          this.modform.isFrontDisplay = false
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 更新修改后的数据
    updateSubject () {
      const { subjectName, isFrontDisplay } = this.modform
      this.$refs.modform.validate(async (valid) => {
        if (valid) {
          try {
            const res = await update({ id: this.id, subjectName, isFrontDisplay })
            console.log(res)
            this.$message.success('修改学科成功')
            this.dialogFormVisibleMod = false
            // 重新加载表格
            this.getSubjects()
          } catch (err) {
            console.log(err)
            this.$message.error('修改学科失败')
            this.dialogFormVisibleMod = false
          }
        }
      })
    },
    // -- 删除学科 --
    delSubject (id) {
      // 判断
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 删除操作
        const res = await remove({ id })
        console.log(res)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getSubjects()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped lang='less'>
  .text {
    font-size: 14px;
  }
  .menu {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .addsub {
      margin-bottom: 20px;
    }
  }
  .subtable {
    margin: 15px 0 20px 0;
  }
  .subpage {
    float: right;
    margin-bottom: 20px;
  }
</style>
